package com.ihighest.app.infox.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.transform.Templates;

import org.json.JSONException;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.tools.DateTimePickDialogUtil;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 企业入驻
 * 
 * @author lkx Created at 2015-10-14 上午9:43:51
 * @version 1.0
 */
public class EnterpriseEnteringActivity extends BaseActivity implements OnClickListener {
	private ActivityTitle title;
	private EditText enterpriseName, enterpriseType, enterprisePerson, businessScope, enterpriseMomo, enterpriseSlogan;
	private TextView enterpriseTime;
	private ImageView enterpriseImg, businessImg;// 营业执照，企业logo

	private Bitmap myBitmap;
	private static final String PHOTO_FILE_NAME = "businessimg.jpg";
	private File mfile;
	private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;// 结果
	private ApiParam param;
	File fTemp = null;// 临时文件
	static Bitmap bitmap = null;
	private int choose;// 选择的是营业执照还是企业logo的标示
	private final String initStartDateTime = "1980年10月31日"; // 初始化开始时间

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.infox_activity_enterprise_entering);
		initView();
	}

	/**
	 * 初始化绑定
	 * 
	 * 
	 * @author lkx Created at 2015-10-13 下午7:22:45
	 */
	private void initView() {
		mfile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
		param = ApiParam.create();
		title = (ActivityTitle) findViewById(R.id.enterpriseEnteringActivityTitle);
		title.setTitle("企业入驻");
		title.setViewVersible(title.titleBack, title.rightText);
		title.setViewGone(title.titleMsg, title.titleRefresh);
		title.setRightTextViewText("提交");
		enterpriseName = (EditText) findViewById(R.id.edt_enterpriseName);
		enterpriseType = (EditText) findViewById(R.id.edt_enterpriseType);
		enterprisePerson = (EditText) findViewById(R.id.edt_enterpriseLegalPerson);
		enterpriseTime = (TextView) findViewById(R.id.edt_enterpriseCreateDate);
		businessScope = (EditText) findViewById(R.id.edt_enterpriseBusinessScope);
		enterpriseMomo = (EditText) findViewById(R.id.edtInformation);
		enterpriseSlogan = (EditText) findViewById(R.id.edt_enterpriseSlogan);
		enterpriseImg = (ImageView) findViewById(R.id.businessLicenseImgFrontage);
		businessImg = (ImageView) findViewById(R.id.businessLogo);
		title.rightText.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				judgeData();
			}

		});
		enterpriseTime.setOnClickListener(this);
		enterpriseImg.setOnClickListener(this);
		businessImg.setOnClickListener(this);
	}

	/**
	 * 选择图片
	 * 
	 * 
	 * @author lkx Created at 2015-11-18 上午10:32:26
	 */
	private void chooseImg() {
		new AlertDialog.Builder(EnterpriseEnteringActivity.this).setTitle("选择图片获取方式")
				.setNegativeButton("相册", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();

						// 激活系统图库，选择一张图片
						Intent intent = new Intent(Intent.ACTION_PICK);
						intent.setType("image/*");
						startActivityForResult(intent, PHOTO_REQUEST_GALLERY);

					}
				}).setPositiveButton("拍照", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int whichButton) {

						Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
						// 判断存储卡是否可以用，可用进行存储
						if (hasSdcard()) {
							// ContentValues values = new
							// ContentValues();
							// photoUri =
							// EnterpriseEnteringActivity.this.getContentResolver().insert(
							// MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
							// values);
							intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mfile));
						}
						startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
					}
				}).show();
	}

	/**
	 * 是否存在sd卡
	 * 
	 * @return
	 * 
	 * @author lkx Created at 2015-10-17 上午10:53:34
	 */
	private boolean hasSdcard() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 验证数据
	 * 
	 * 
	 * @author lkx Created at 2015-11-17 上午9:15:10
	 */
	private void judgeData() {
		if (TextUtils.isEmpty(enterpriseName.getText().toString()) || TextUtils.isEmpty(enterprisePerson.getText().toString())
				|| TextUtils.isEmpty(enterpriseType.getText().toString()) || TextUtils.isEmpty(enterpriseTime.getText().toString())
				|| TextUtils.isEmpty(businessScope.getText().toString()) || TextUtils.isEmpty(enterpriseSlogan.getText().toString())) {
			ToastKit.showShort(EnterpriseEnteringActivity.this, "请您填写全部必填项");

		} else {
			if (fTemp == null) {
				ToastKit.showShort(EnterpriseEnteringActivity.this, "请选择营业执照");
			} else {
				if (TextUtils.isEmpty(enterpriseMomo.getText().toString())) {
					ToastKit.showShort(EnterpriseEnteringActivity.this, "请输入简介信息");
				} else {
					if (TextUtils.isEmpty(SharedPreferencesKit.getString(EnterpriseEnteringActivity.this, Const.SP_KEY_USER_ID))) {
						ToastKit.showShort(EnterpriseEnteringActivity.this, Const.UN_LOGIN_ALERT);
					} else {
						commitData();
					}

				}
			}
		}

	}

	/**
	 * 提交数据
	 * 
	 * 
	 * @author lkx Created at 2015-11-18 上午10:14:15
	 */
	private void commitData() {
		title.rightText.setClickable(false);
		param.addParam("uname", enterpriseName.getText().toString());
		param.addParam("advertise", enterpriseSlogan.getText().toString());
		param.addParam("type", enterpriseType.getText().toString());
		param.addParam("manage", enterprisePerson.getText().toString());
		param.addParam("date", enterpriseTime.getText().toString());
		param.addParam("scope", businessScope.getText().toString());
		param.addParam("memo", enterpriseMomo.getText().toString());
		Api.post("apply/enterprise", param, new ApiCallback(EnterpriseEnteringActivity.this) {

			@Override
			public void handleSuccess(ApiResult result) {
				if (result.getCode() == 100) {
					finish();
				} else {
					ToastKit.showShort(EnterpriseEnteringActivity.this, result.getMsg());
				}

			}

			@Override
			public void handleFailure(Exception e, String msg) {
				// TODO Auto-generated method stub
				title.rightText.setClickable(true);
			}
		}, EnterpriseEnteringActivity.this);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PHOTO_REQUEST_GALLERY) {
			if (data != null) {
				// 得到图片的全路径

				Uri uri = data.getData();
				crop(uri);
			}

		} else if (requestCode == PHOTO_REQUEST_CAMERA) {
			if (hasSdcard()) {
				if (mfile != null) {
					crop(Uri.fromFile(mfile));
				}

			} else {
				Toast.makeText(EnterpriseEnteringActivity.this, "未找到存储卡，无法存储照片！", 0).show();
			}

		} else if (requestCode == PHOTO_REQUEST_CUT) {
			try {
				myBitmap = data.getParcelableExtra("data");
				if (choose == 1) {
					this.enterpriseImg.setImageBitmap(myBitmap);
				} else if (choose == 2) {
					this.businessImg.setImageBitmap(myBitmap);
				}
				bitMapToFile();
				boolean delete = mfile.delete();

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 图片裁剪
	 * 
	 * @param uri
	 * 
	 * @author lkx Created at 2015-10-17 上午10:58:44
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		// intent.putExtra("aspectX", 1);
		// intent.putExtra("aspectY", 1);
		// // 裁剪后输出图片的尺寸大小
		// intent.putExtra("outputX", 250);
		// intent.putExtra("outputY", 250);
		// 图片格式
		intent.putExtra("outputFormat", "JPEG");
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	/**
	 * 图片转换为file文件
	 * 
	 * 
	 * @author lkx Created at 2015-11-17 上午9:57:45
	 */
	private void bitMapToFile() {
		if (myBitmap != null) {

			try {
				File tempFile = File.createTempFile("businessLogo", ".jpg");
				fTemp = File.createTempFile("businessImg", ".jpg");
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fTemp));

				myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
				if (choose == 1) {
					param.addParam("pic", fTemp);
				}
				if (choose == 2) {
					param.addParam("LOGO", tempFile);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.businessLicenseImgFrontage:
			choose = 1;
			chooseImg();

			break;

		case R.id.businessLogo:
			choose = 2;
			chooseImg();

			break;
		case R.id.edt_enterpriseCreateDate:
			DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(EnterpriseEnteringActivity.this, initStartDateTime);
			dateTimePicKDialog.dateTimePicKDialog(enterpriseTime);

			break;

		}
	}
}
